package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 服务器启动时，执行rabbitTemplate初始化，设置确认函数和回退函数
 * ApplicationEvent      一些子事件的父类。
 * ApplicationReadyEvent 具体子事件。表示应用程序启动好，IOC容器初始化好，存在相关bean对象了。再进行相关的初始化。
 * 也可以使用相关的注解替代： @EventListener
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setUpInitRabbitTemplete();
    }


    private void setUpInitRabbitTemplete() {

        //确认回调
        /**
         * correlationData 关联数据
         * ack 返回结果
         * cause 原因
         */
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack){
                log.info("消息发送成功"+correlationData);
            }else {
                log.error("消息发送失败"+cause);
                //重发消息
                this.retrySendMsg(correlationData);
            }
        });
        //回退回调
        this.rabbitTemplate.setReturnsCallback(returned -> {
            log.error("Result:"+returned.getMessage()+"\nexchange:"+returned.getExchange()
            +"\nroutingKey:"+returned.getRoutingKey()+"\nreplyText:"+returned.getReplyText()
            +"\nreplyCode:"+returned.getReplyCode());
            //获取关联数据
            Message message = returned.getMessage();
            MessageProperties messageProperties = message.getMessageProperties();
            String correlationId = messageProperties.getHeader("spring_returned_message_correlation");
           String correlationIdStr = (String) redisTemplate.opsForValue().get(correlationId);
           //转换成数据
            GuiguCorrelationData guiguCorrelationData = JSON.parseObject(correlationIdStr, GuiguCorrelationData.class);
            if (guiguCorrelationData.isDelay()){
                log.info("延迟插件回退不进行消息重发");
                return;
            }
            this.retrySendMsg(guiguCorrelationData);
        });
    }

    private void retrySendMsg(CorrelationData correlationData) {
        GuiguCorrelationData guiguCorrelationData=(GuiguCorrelationData) correlationData;
        int retryCount = guiguCorrelationData.getRetryCount();
        if (retryCount>=3){
            log.error("生产者超过最大重试次数，将失败的消息存入数据库用人工处理；给管理员发送邮件；给管理员发送短信；");
            return;
        }
        retryCount++;
        guiguCorrelationData.setRetryCount(retryCount);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {}
        redisTemplate.opsForValue().set(guiguCorrelationData.getId(),guiguCorrelationData,10, TimeUnit.MINUTES);
        if (guiguCorrelationData.isDelay()){
            //延迟
            MessagePostProcessor messagePostProcessor=(message) -> {
                message.getMessageProperties().setDelay(guiguCorrelationData.getDelayTime()*1000);
                return message;
            };
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),messagePostProcessor,
                    guiguCorrelationData);
        }else {
            //重发消息 普通
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    guiguCorrelationData);
        }
    }
}
